//
//  GPSManager.swift
//  XXIOT
//
//  Created by xx on 2024/8/26.
//

import UIKit
import Foundation
import CoreLocation


class GPSManager: NSObject {

    func haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Double {
        let R = 6371.0 // 地球半径，单位：公里
        
        let dLat = (lat2 - lat1) * .pi / 180.0
        let dLon = (lon2 - lon1) * .pi / 180.0
        
        let a = sin(dLat / 2) * sin(dLat / 2) +
                cos(lat1 * .pi / 180.0) * cos(lat2 * .pi / 180.0) *
                sin(dLon / 2) * sin(dLon / 2)
        
        let c = 2 * atan2(sqrt(a), sqrt(1 - a))
        
        return R * c // 返回距离，单位：公里
    }

    func calculateAngle(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Double {
        let dLat = lat2 - lat1
        let dLon = lon2 - lon1
        
        let angle = atan2(dLon, dLat) * (180.0 / .pi) // 返回角度
        return angle >= 0 ? angle : angle + 360 // 确保角度为正值
    }
    
    func test(){
        // 示例用法
        let lat1 = 39.9042 // 第一个点的纬度
        let lon1 = 116.4074 // 第一个点的经度
        let lat2 = 34.0522 // 第二个点的纬度
        let lon2 = -118.2437 // 第二个点的经度

        let distance = haversine(lat1: lat1, lon1: lon1, lat2: lat2, lon2: lon2)
        let angle = calculateAngle(lat1: lat1, lon1: lon1, lat2: lat2, lon2: lon2)

        print("距离: \(distance) 公里")
        print("角度: \(angle) 度")
    }
}


